<template>
  <div class="pane-account">
    <el-form
      label-width="60px"
      size="large"
      :model="account"
      :rules="accountRules"
      hide-required-asterisk
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input
          prefix-icon="user"
          v-model="account.name"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          prefix-icon="lock"
          v-model="account.password"
          show-password
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { localCache } from '../../../utils/cache'
import useLoginStore from '@/store/login/login'

const CACHE_NAME = 'task-managenment-system/name'
const CACHE_PASSWORD = 'task-managenment-system/password'

// 定义account数据
const account = reactive({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})

// 定义校验规则
const accountRules = {
  name: [
    {
      required: true,
      message: '请输入账号信息',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z0-9]{3,20}$/,
      message: '账号信息为3-20位字母或数字组成',
      trigger: 'change'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码信息',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z0-9]{3,}$/,
      message: '密码必须为3位以上字母或数字组成',
      trigger: 'change'
    }
  ]
}

// 执行账号登录逻辑
const formRef = ref()
const loginStore = useLoginStore()
function loginAction(isRemPwd) {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 1.获取用户输入的账号密码
      const name = account.name
      const password = account.password
      // 2.向服务器发送网络请求，并携带账号密码
      loginStore.loginAccountRequest({ account: name, password }).then((res) => {
        console.log('res: ', res)
        if (res.code === 0) {
          // 3.判断是否需要记住密码
          if (isRemPwd) {
            localCache.setCache(CACHE_NAME, name)
            localCache.setCache(CACHE_PASSWORD, password)
          } else {
            localCache.removeCache(CACHE_NAME)
            localCache.removeCache(CACHE_PASSWORD)
          }
        } else {
          ElMessage.error(res.message)
        }
      }).catch((err) => {
        console.log(err)
      })
    } else {
      ElMessage.error('请输入账号密码后再操作~')
    }
  })
}

defineExpose({
  loginAction
})

</script>

<style lang="scss" scoped>

</style>